package com.lysj.admin.master.auth.service;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.lysj.admin.master.CacheManager;
import com.lysj.admin.master.auth.domain.User;
import com.lysj.admin.master.common.CommonConstant;
import com.lysj.admin.master.common.authentication.AuthenticationInterface;
import com.lysj.admin.master.common.authentication.AuthenticationResultVO;
import com.lysj.admin.master.common.cache.RedisKeyEnum;
import com.lysj.admin.master.common.cache.RedisUtil;
import com.lysj.admin.master.common.jwt.JwtUtil;
import com.lysj.admin.master.common.web.ParamUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.Set;

/**
 * @author Created by zk on 2019-12-06 16:27
 * @description :代理商权限
 */
@Service
public class AgentAuthentication implements AuthenticationInterface {
    @Resource
    private UserService userService;
    @Resource
    private RedisUtil redisUtil;


    @Override
    public String getIss() {
        return CommonConstant.AGENT_ISSUER;
    }

    @Override
    public AuthenticationResultVO authentication(String token, Map<String, Object> payloadMap, String path) {
        String userId = (String) payloadMap.get(CommonConstant.JWT_SUB);
        if (ParamUtil.isBlank(userId)) {
            return new AuthenticationResultVO(false, "token信息异常,请重新登录");
        }
        User user = redisUtil.get(RedisKeyEnum.USER,userId,() -> userService.getById(userId));
//        User user = userService.getById(userId);
        if (user == null || CommonConstant.DEL_FLAG.equals(user.getDelFlag())) {
            return new AuthenticationResultVO(false, "查无该token信息,请重新登录");
        }
        String key = user.getUsername();
        DecodedJWT jwt;
        try {
            jwt = JwtUtil.verifier(token, key);
        } catch (Exception e) {
            e.printStackTrace();
            return new AuthenticationResultVO(false, "token校验有误,请重新登录");
        }
        //判断是否拥有该路径权限，目前策略为数据库若无记录的路径，则全部放行
        //获取该path支持的角色列表
        Set<String> roleIds = CacheManager.agentPermissionRoleCache.get(path);
        //若角色列表不为null，则需要进行权限判断
        if (roleIds != null) {
            //若在角色列表中匹配不到该角色，则为无权限
            if (!roleIds.contains(userId)) {
                return new AuthenticationResultVO(false, "您尚未拥有该权限");
            }
        }
        //判断用户token是否需要刷新
        Date expires = jwt.getExpiresAt();
        Date now = new Date();
        if ((now.getTime() - expires.getTime()) < CommonConstant.ADMIN_TOKEN_REFRESH * 60 * 1000) {
            token = JwtUtil.copyToken(payloadMap, CommonConstant.ADMIN_TOKEN_EXPIRATION, key);
        }
        return new AuthenticationResultVO(true, token);
    }


}
